﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Holoville.HOTween;

public partial class MessageScene : Scene
{
	public MailMessageScrollView mailMessageScrollView;
	public UIGrid mailMessageGrid;
	public GameObject mailMessageCell;
	public ObjectPooler mailMessageObjectPooler;

	int lastOpenedMailMessageCellIndex = -1;

	Dictionary<int, MailMessage> mailMessageDictionary = new Dictionary<int, MailMessage>();
	Dictionary<int, GameObject> mailMessageObjectDictionary = new Dictionary<int, GameObject>();

	public void SelectAllMailMessageCheckBox()
	{
		bool checkValue = false;

		foreach (KeyValuePair<int, GameObject> pair in mailMessageObjectDictionary)
		{
			if (selectAllMailMessageToggle.value == false)
				break;

			if (pair.Value.GetComponent<MailMessageCell>().checkBox.IsChecked == false)
			{
				checkValue = true;
				break;
			}
		}

		selectAllMailMessageToggle.value = checkValue;

		List<int> keyList = new List<int>(mailMessageObjectDictionary.Keys);

		foreach (int key in keyList)
		{
			mailMessageObjectDictionary[key].GetComponent<MailMessageCell>().checkBox.IsChecked = checkValue;
		}
	}

	public void SetMailMessageCheckBox(int index, bool isChecked, bool applyObject = false)
	{
		if (applyObject) mailMessageObjectDictionary[index].GetComponent<MailMessageCell>().checkBox.IsChecked = isChecked;
	}

	void ClearMailMessageData()
	{
		lastOpenedMailMessageCellIndex = -1;
		mailMessageDictionary.Clear();

		foreach (KeyValuePair<int, GameObject> pair in mailMessageObjectDictionary)
		{
			// TODO: need for refectorying
			pair.Value.GetComponent<MailMessageCell>().checkBox.IsChecked = false;
			NGUITools.SetActive(pair.Value, false);
		}

		mailMessageObjectDictionary.Clear();
	}

	public void LoadMailMessage()
	{
		ClearMailMessageData();
		
		NetworkManager.Instance.C2S_MSG_LIST<List<MailMessage>>(1, (responseData) => {
			GameObject g = null;
			int idx = 0;

			ShowBadge(BadgeType.MailMessage);

			if (responseData.data.Count <= 0)
			{
				//NGUITools.SetActive(emptyListView, true);
				SetEmptyListView(true);
				return;
			}

			//NGUITools.SetActive(emptyListView, false);
			SetEmptyListView(false);

			responseData.data = responseData.data.OrderByDescending(mailMessage=>mailMessage.date).ToList();

			foreach (MailMessage mm in responseData.data)
			{
				g = mailMessageObjectPooler.GetPooledObject();
				g.transform.parent = mailMessageGrid.transform;
				g.transform.localScale = Vector3.one;
				g.transform.localRotation = Quaternion.identity;
				
				MailMessageCell mmc = g.GetComponent<MailMessageCell>();
				mmc.indexPath = idx;
				mmc.receiveDateLabel.text =  DatetimeToString(mm.date);
				mmc.remainTimeLabel.text = DatetimeToFomattedString(mm.date);
				mmc.titleLabel.text = string.Format(Localization.Get("uiMailboxNoteTitle"), mm.ouserName);
				mmc.contentLabel.text = string.Format("{0}", mm.body);

				mailMessageObjectDictionary.Add (idx, g);
				mailMessageDictionary.Add (idx, mm);

				NGUITools.SetActive(g, true);

				g.animation["View_message Open"].time = 0.0f;
				g.animation["View_message Open"].enabled = true;
				g.animation.Sample();
				g.animation["View_message Open"].enabled = false;

				idx++;
			}
			
			mailMessageGrid.Reposition();
			mailMessageScrollView.ResetPosition();

		});

	}
	
	public void FlipOpenMailMessageCell(int selectedIndexPath)
	{
		int tweenStartIndex = 0;
		int tweenEndIndex = 0;
		float tweenValue = 0.0f;

		mailMessageObjectDictionary[selectedIndexPath].GetComponent<MailMessageCell>().animation.Play("View_message Open");

		if (lastOpenedMailMessageCellIndex >= 0)
		{
			mailMessageObjectDictionary[lastOpenedMailMessageCellIndex].GetComponent<MailMessageCell>().animation.Play("View_message Close");

			if (selectedIndexPath < lastOpenedMailMessageCellIndex)
			{
				tweenStartIndex = selectedIndexPath + 1;
				tweenEndIndex = lastOpenedMailMessageCellIndex;
				tweenValue = -519.0f;
			}
			else
			{
				tweenStartIndex = lastOpenedMailMessageCellIndex + 1;
				tweenEndIndex = selectedIndexPath;
				tweenValue = 519.0f;
			}
		}
		else
		{
			tweenStartIndex = selectedIndexPath + 1;
			tweenEndIndex = mailMessageObjectDictionary.Count - 1;
			tweenValue = -519.0f;
		}

		for (int i = tweenStartIndex; i <= tweenEndIndex; i++)
		{
			HOTween.To(mailMessageObjectDictionary[i].transform, 0.3f, new TweenParms().Prop("localPosition", new Vector3(0.0f, tweenValue, 0.0f), true));
		}

		lastOpenedMailMessageCellIndex = selectedIndexPath;

	}
	
	public void FlipCloseMailMessageCell(int selectedIndexPath)
	{
		int tweenStartIndex = selectedIndexPath + 1;
		int tweenEndIndex = mailMessageObjectDictionary.Count - 1;
		float tweenValue = 519.0f;

		mailMessageObjectDictionary[selectedIndexPath].GetComponent<MailMessageCell>().animation.Play("View_message Close");

		for (int i = tweenStartIndex; i <= tweenEndIndex; i++)
		{
			HOTween.To(mailMessageObjectDictionary[i].transform, 0.3f, new TweenParms().Prop("localPosition", new Vector3(0.0f, tweenValue, 0.0f), true));
		}

		lastOpenedMailMessageCellIndex = -1;
	}
	
	public void OnClick_RemoveMailMessage()
	{
		bool isShowAlert = false;
		foreach (KeyValuePair<int, GameObject> pair in mailMessageObjectDictionary)
		{
			if (pair.Value.GetComponent<MailMessageCell>().checkBox.IsChecked == true)
			{
				isShowAlert = true;
				break;
			}
		}

		if (isShowAlert)
		{
			Popup_TwoButton pt = PopupManager.PushPopup(PopupKind.TwoButton) as Popup_TwoButton;
			pt.SetPopupWithTitleAndBody(Localization.Get("uiCommonTextwarning"), Localization.Get("uiPopupMailboxCaution2"));
			pt.SetPopupWithYesNoString(Localization.Get("uiCommonTextCheck"), Localization.Get("uiCommonTextCancel"));
			pt.SetEventOK(gameObject, "OnClick_RemoveMailMessagePostProcess");
		}
	}

	public void OnClick_RemoveMailMessagePostProcess()
	{
		foreach (KeyValuePair<int, GameObject> pair in mailMessageObjectDictionary)
		{
			if (pair.Value.GetComponent<MailMessageCell>().checkBox.IsChecked == true)
			{
				RemoveMailMessage(pair.Key, 1);
			}
		}
	}

	public void OnClick_RefreshMailMessage()
	{
		Debug.Log("OnClick_RefreshMailMessage");
		LoadMailMessage();
	}

	void RemoveMailMessage(int selectedIndexPath, int msgType)
	{
		NetworkManager.Instance.C2S_MSG_REMOVE(mailMessageDictionary[selectedIndexPath].id, msgType, (responseData) => {

			if (responseData.ecode != 0)
			{
				PopupUtility.OneButtonErrorPopup(responseData.ecode);
				return;
			}

			HOTween.To (mailMessageObjectDictionary[selectedIndexPath].transform, 0.5f, new TweenParms().Prop("localPosition", new Vector3(1700.0f, 0.0f, 0.0f), true).Ease(EaseType.EaseInOutQuint).OnComplete( ()=> {
				mailMessageDictionary.Remove(selectedIndexPath);
				
				NGUITools.SetActive(mailMessageObjectDictionary[selectedIndexPath], false);
				mailMessageObjectDictionary.Remove(selectedIndexPath);
				
				mailMessageGrid.Reposition();
			}));

			//LoadMailMessage();
		});
	}

	public void OnClick_WriteMessageTab()
	{
		OnClick_WriteMessageTabWithIndexPath(-1);
	}

	public void OnClick_WriteMessageTabWithIndexPath(int selectedIndexPath)
	{
		receiverId = -1;

		Popup_WriteMessage pw = PopupManager.PushPopup(PopupKind.WriteMessage) as Popup_WriteMessage;

		if (selectedIndexPath >= 0)
		{
			pw.receiverId = mailMessageDictionary[selectedIndexPath].ouserId;
			pw.receiverNameInput.value = mailMessageDictionary[selectedIndexPath].ouserName;
		}
		else
		{
			pw.receiverId = -1;
		}
	}
}